package home.project;

import haxe.io.Bytes;
import haxe.io.BytesOutput;

/**
 * ...
 * @author an.vuongngocduy
 */
class Base64
{
	private static var __lookup:Array<Int> = [
		-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
		-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
		-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63,
		52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1,
		-1,  0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14,
		15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1,
		-1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
		41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1,
		-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
		-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
		-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
		-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
		-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
		-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
		-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
		-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
	];
	
	public static function decode(input:String):Bytes
	{
		var res:BytesOutput = new BytesOutput();
		
		var i:Int = 0;
		while (true)
		{
			if (input.charAt(i) == " " || input.charAt(i) == "\n" || input.charAt(i) == "\r")
			{
				i++;
				continue;
			}
			
			var remain:Int = input.length - i;
			
			if (remain <= 3) break;
			
			var a:Int = __lookup[input.charCodeAt(i)];
			var b:Int = __lookup[input.charCodeAt(i + 1)];
			var c:Int = __lookup[input.charCodeAt(i + 2)];
			var d:Int = __lookup[input.charCodeAt(i + 3)];
			
			if (a != -1 && b != -1)
				res.writeByte(((a & 0x3F) << 2) | ((b & 0x30) >> 4));
			 			
			if (b != -1 && c != -1)	
				res.writeByte(((b & 0x0F) << 4) | ((c & 0x3C) >> 2));
		
			if (c != -1 && d != -1)
				res.writeByte(((c & 0x03) << 6) | (d & 0x3F));
			
			i += 4;
		} 
		return res.getBytes();
	}
}